import sys
import os
sys.path.append(os.getcwd() + '/dao')
sys.path.append(os.getcwd() + '/entity')

from flask import Flask
from flask import request
import json

from db import POOL
from Msg import Msg
from User import User


app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def home():
    return '<h1>Home</h1>'


@app.route('/signin', methods=['GET'])
def signin_form():
    return '''<form action="/signin" method="post">
              <p><input name="username"></p>
              <p><input name="password" type="password"></p>
              <p><button type="submit">Sign In</button></p>
              </form>'''


@app.route('/signin', methods=['POST'])
def signin():
    # 需要从request对象读取表单内容：
    if request.form['username'] == 'admin' and request.form['password'] == 'password':
        return '<h3>Hello, admin!</h3>'
    return '<h3>Bad username or password.</h3>'


@app.route('/form', methods=['get'])
def form():
    args = request.args
    name = args.get("name")
    addr = args.get("addr")
    age = args.get("age")
    print(age, name, addr)
    return '{name:%s,age:%s}' % (name, age)


@app.route('/rest', methods=['post'])
def rest():
    data = str(request.get_data(), encoding="utf-8")
    print(data)
    return '{data:%s}' % (data)


@app.route('/rest_json', methods=['POST'])
def rest_json():
    json_data = request.get_json()

    map_1 = {
        "name": json_data['name'],
        "age": json_data['age']
    }

    return json.dumps(map_1)


@app.route('/rest_user_save', methods=['POST'])
def rest_user_save():
    """
        读取json 请求数据
    :return:
    """
    json_data = request.get_json()
    conn = POOL.connection()
    cursor = conn.cursor()
    try:
        sql = "INSERT INTO `user` (`name`, `addr`,`age`) VALUES ('%s', '%s',%s)" % \
              (json_data['name'], json_data['addr'], json_data['age'])
        cursor.execute(sql)
        id = int(cursor.lastrowid)
        msg = {
            "info": {
                "name": json_data['name'],
                "addr": json_data['addr'],
                "age": json_data['age'],
                "id": id
            },
            "msg": "ok",
            "status": 200
        }
        return json.dumps(msg)

    except BaseException as e:
        print(e)
    finally:
        conn.commit()
        cursor.close()
        conn.close()

    return None


@app.route('/rest_all_user_read', methods=['GET'])
def rest_all_user_read():
    """
        只有字典 和 json能相互转换。
    :return:
    """
    conn = POOL.connection()
    try:
        cursor = conn.cursor()
        sql = "select * from `user` "
        cursor.execute(sql)
        results = cursor.fetchall()
        users = []
        for row in results:

            id = row[0]
            age = row[1]
            name = row[2]
            addr = row[3]
            remark = row[4]
            user = User(name, id, addr, age, remark).__dict__
            users.append(user)

        msg = Msg(200, users, True).__dict__
        return json.dumps(msg)

    except BaseException as e:
        print(e)
        return e


@app.route('/query_user_by_id', methods=['GET'])
def query_user_by_id():
    args = request.args
    id = int(args.get('id'))

    conn = POOL.connection()
    try:
        cursor = conn.cursor()
        sql = "select * from `user` where `id` = %s" % id
        cursor.execute(sql)
        results = cursor.fetchall()
        users = []
        for row in results:

            id = row[0]
            age = row[1]
            name = row[2]
            addr = row[3]
            remark = row[4]
            user = User(name, id, addr, age, remark).__dict__
            users.append(user)

        msg = Msg(200, users, True).__dict__
        return json.dumps(msg)

    except BaseException as e:
        print(e)
        return e


if __name__ == '__main__':
    app.run(port=9090)